import { Button, Divider,message, Tabs ,Popconfirm,notification} from 'antd'
import React, { useState, useRef } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table'
import { connect, Link } from 'umi'
import { getSecondmentList, deleteEmployeeSecondment,saveAndUpdateEmployeeSecondment,employeeSecondmentBpm} from './service'
import CreateForm from './components/CreateForm'
import moment from 'moment'
import {secondmentStatusList} from "@/utils/constant";
const { TabPane } = Tabs;

const TableList = () => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [visible, setVisible] = useState(null);
  const [record, setRecord] = useState(null);
  const [loading, setLoading] = useState(false);
  const [tabKey, setTabKey] = useState('0');

  const saveOrEditSecondment = (record,type) => {
    if(record){
      record.type = type;
      setRecord(record);
    }
    setVisible(true);
  };

  const delSecondment = (id) => {
    setLoading(true);
    deleteEmployeeSecondment(id).then(res => {
      if (res.flag) {
        message.success(`删除成功！`);
        actionRef.current.reload();
      } else {
        message.error(`删除失败，错误:` + res.error);
      }
      setLoading(false);
    })
  };

  const sendEmployeeSecondmentBpm = (id) => {
    employeeSecondmentBpm(id).then(res => {
      if (res.flag){
        window.open(res.data);
        message.success('bpm发起成功！');
      }else {
        message.error(`发起失败，错误:` + res.error);
      }
    });
  };

  const tabChange = (key) =>{
    setTabKey(key);
    if (key==='0'){
      actionRef && actionRef.current.reload();
    }else {
      actionRef2 && actionRef2.current.reload();
    }
  };

  const handleCancel = () => {
    setRecord(null);
    setVisible(false);
  };

  const handleSubmit = (values) => {
    setLoading(true);
    saveAndUpdateEmployeeSecondment(values).then(res => {
      if(res.flag){
        message.success('操作成功！');
        handleCancel();
        actionRef.current.reload()
      }else{
        notification.error({
          message: `请求错误 ${res.status}`,
          description: res.error,
        });
      }
      setLoading(false);
    });
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (item, record) => (
        <Link to={`/info/details/${record.oid}`}>{item}</Link>
      ),
    },
    {
      title: '原公司',
      dataIndex: 'orgName',
      hideInSearch: true,
    },
    {
      title: '原部门',
      dataIndex: 'unitName',
      hideInSearch: true,
    },
    {
      title: '调入公司',
      dataIndex: 'secondmentOrgName',
      hideInSearch: true,
    },
    {
      title: '调入部门',
      dataIndex: 'secondmentUnitName',
      hideInSearch: true,
    },
    {
      title: '调出时间',
      dataIndex: 'outTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '预计借调时长',
      dataIndex: 'countdown',
      hideInSearch: true,
      render: (text, record) => {
        let ctm = moment(record.outTime);
        let etm = moment(record.expectedEndTime);
        return etm.diff(ctm, 'days') + '天'
      }
    },
    {
      title: '预计借调结束日期',
      dataIndex: 'expectedEndTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '实际结束日期',
      dataIndex: 'endTime',
      hideInSearch: true,
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '调入部门承担成本比例',
      dataIndex: 'proportion',
      hideInSearch: true,
      render: (text) => {
        return text + '%';
      },
    },
    {
      title: '借调原因',
      dataIndex: 'reason',
      hideInSearch: true,
      ellipsis: true,
      width:120
    },
    {
      title: '创建人',
      dataIndex: 'applyUserName',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: secondmentStatusList[0].label, status: 'Default' },
        1: { text: secondmentStatusList[1].label, status: 'Processing'},
        2: { text: secondmentStatusList[2].label, status: 'Success' },
        3: { text: secondmentStatusList[3].label,status: 'Processing' },
        4: { text: secondmentStatusList[4].label,status: 'Default' },
      },
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width:'10%',
      // hideInTable: tabKey !== '0',
      render: (item, record) => (
        <>
          {(record.status === 0) && <>
            <a onClick={() => saveOrEditSecondment(record,null)}>修改</a>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认删除?`} onConfirm={() => delSecondment(record.id)} okText="是" cancelText="否">
              <a>删除</a>
            </Popconfirm>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认发起?`} onConfirm={() => sendEmployeeSecondmentBpm(record.id)} okText="是" cancelText="否">
              <a>发起</a>
            </Popconfirm>
          </>}
          {(record.status === 1) && <><a onClick={() => window.open(record.bpmUrl)}>查看流程</a></>}
          {(record.status === 2) && <><a onClick={() => saveOrEditSecondment(record,'end')}>结束借调</a></>}
          {(record.status === 3) && <><a onClick={() => window.open(record.bpmEndUrl)}>查看流程</a></>}
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <Tabs animated={false} activeKey={tabKey} onChange={tabChange}>
        <TabPane forceRender tab="未办理" key="0">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            toolBarRender={(action, { selectedRows }) => [
              <Button type="primary" onClick={() => saveOrEditSecondment(null,null)}>新建</Button>,
            ]}
            request={(params) => getSecondmentList(params,[0,1,2,3])}
            columns={columns}
          />
        </TabPane>
        <TabPane forceRender tab="已办理" key="1">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => getSecondmentList(params,[4])}
            columns={columns}
          />
        </TabPane>
      </Tabs>
      <CreateForm
        record={record}
        loading={loading}
        visible={visible}
        onCancel={handleCancel}
        onSubmit={handleSubmit}
      />
    </PageHeaderWrapper>
  )
};

export default connect(() => ({
}))(TableList)
